package com.ruoyi.module.business;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.utils.ErpFileAnalysisUtil;
import com.ruoyi.module.domain.BookInfo;
import com.ruoyi.module.domain.FtpFile;
import com.ruoyi.module.service.CmBookInfoService;
import com.ruoyi.module.service.CmFtpFileService;
import com.ruoyi.module.utils.ErpFileLineHandler;
import com.ruoyi.module.utils.ErpFileStorage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.compress.utils.Sets;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
@RequiredArgsConstructor
public class CmErpBusiness {
    private final CmFtpFileService ftpFileService;
    private final CmBookInfoService bookInfoService;

    @Value("${agent.file.prefix:100029,100017}")
    private String suitableFileStr;

    /**
     * 每分钟检查一次又没有新文件
     */
    public void checkFile() {
        try {
            Set<String> suitableFilePrefix = Sets.newHashSet(suitableFileStr.split(","));

            log.info("系统开启任务检查文件前缀：{}", suitableFilePrefix);
            List<FTPFile> files = ErpFileAnalysisUtil.getFiles(suitableFilePrefix);

            List<String> fileNames = files.stream().map(FTPFile::getName).collect(Collectors.toList());
            List<FtpFile> containsFtpFiles = ftpFileService.querySelective(fileNames);

            List<String> containsNames = containsFtpFiles.stream().map(FtpFile::getName).collect(Collectors.toList());

            List<FtpFile> ftpFiles = files.stream()
                    .filter(v -> suitableFilePrefix.contains(v.getName().split("_")[0]))
                    .filter(v -> !containsNames.contains(v.getName())).map(v -> {
                        FtpFile file = new FtpFile();
                        file.setType(v.getType());
                        file.setName(v.getName());
                        file.setTimestamp(LocalDateTime.ofEpochSecond(v.getTimestamp().getTimeInMillis() / 1000, 0, ZoneOffset.UTC));
                        file.setSize(v.getSize());
                        file.setStatus((byte) 1);
                        return file;
                    }).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(ftpFiles)) {
                ftpFileService.batchInsert(ftpFiles);
            }
            log.info("系统结束任务检查文件");
        } catch (Throwable e) {
            log.info("checkFile: {}", ExceptionUtils.getStackTrace(e));
        }
    }

    /**
     * 每分钟分析文件
     */
    public void analysisFiles() {
        log.info("系统开启任务分析文件");

        try {
            List<FtpFile> ftpFiles = ftpFileService.queryNewFiles();

            ftpFiles.forEach(v -> {
                String name = v.getName();
                log.info("analysisFiles:{}", name);

                String storeId = name.split("_")[0];
                log.info("storeId:{}", storeId);

                ErpFileAnalysisUtil.analysisFile(name, new ErpFileLineHandler(bookInfoService, storeId));

                if (CollectionUtil.isNotEmpty(ErpFileStorage.infos)) {
                    bookInfoService.batchUpdateBookInfo(ErpFileStorage.infos);
                }

                ErpFileStorage.infos.clear();
                v.setLineNum(ErpFileStorage.lineNum);
                v.setStatus((byte) 2);
                ftpFileService.updateCmFtpFile(v);

                ErpFileStorage.lineNum = 0;
            });
        } catch (Exception e) {
            log.error(ExceptionUtils.getStackTrace(e));
        }

        log.info("系统结束任务分析文件");
    }
}
